import Vue from 'vue';
import Utils from './util';
import Config from '../config';

var plus = {
    isWindows: true,
    camera: {
        getCamera() {

        }
    }, 
    device: {
        uuid: '',
    },
    runtime: {
        appid: '',
        version: '',
        install() {

        },
        getProperty() {

        }
    }, 
    os: {
        name: 'Windows'
    }, 
    gallery: {
        pick(successCB, errorCB, options) {
            var filter = [{ name: 'Images', extensions: ['jpg', 'png', 'gif'] }];
            window.ipcRenderer.send('selectFile', filter);
            window.ipcRenderer.once("fileSelected", function(event, file) {
                if (successCB) {
                    successCB(file);
                }
            });
        }
    },
    key: {
        addEventListener(eventName, callback) {
            document.addEventListener(eventName, callback, false);
        }
    }, 
    share: {
        sendWithSystem(msg, successCB, errorCB) {
            vue.$f7.actions.create({
                grid: true,
                buttons: [
                  [
                    {
                      text: '分享到',
                      label: true
                    },
                  ],
                  [
                    {
                      text: '微信',
                      icon: '<img src="' + Config.server + '/images/o_img_wechat.png" width="48"/>',
                      onClick: function() {
                        let popup = vue.$f7.popup.get(".f7-share-popup");
                        if (popup) {
                            popup.open();
                        }
                      }
                    },
                    {
                      text: 'QQ好友',
                      icon: '<img src="' + Config.server + '/images/o_img_qq.png" width="48">',
                      onClick: function() {
                        let _shareUrl = 'https://connect.qq.com/widget/shareqq/iframe_index.html?';
                        _shareUrl += 'url=' + encodeURIComponent(msg.href);
                        _shareUrl += '&title=' + encodeURIComponent(msg.title);
                        window.open(_shareUrl,'_blank');
                      }
                    },
                    {
                      text: 'QQ空间',
                      icon: '<img src="' + Config.server + '/images/o_img_zone.png" width="48">',
                      onClick: function() {
                        let _shareUrl = 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?';
                        _shareUrl += 'url=' + encodeURIComponent(msg.href);
                        _shareUrl += '&showcount=' + 0;
                        _shareUrl += '&desc=' + encodeURIComponent(msg.title); 
                        _shareUrl += '&title=' + encodeURIComponent(msg.title);
                        _shareUrl += '&pics=' + encodeURIComponent(msg.pictures || '');
                        window.open(_shareUrl,'_blank');
                      }
                    },
                  ],
                  [
                    {
                      text: '新浪微博',
                      icon: '<img src="' + Config.server + '/images/o_img_xlwb.png" width="48"/>',
                      onClick: function() {
                        let _shareUrl = 'http://v.t.sina.com.cn/share/share.php?';
                        _shareUrl += 'url='+ encodeURIComponent(msg.href || '');
                        _shareUrl += '&title=' + encodeURIComponent(msg.title); 
                        _shareUrl += '&source=' + encodeURIComponent('');
                        _shareUrl += '&sourceUrl=' + encodeURIComponent('');
                        _shareUrl += '&content=' + 'utf-8';
                        _shareUrl += '&pic=' + encodeURIComponent(msg.pictures || '');
                        window.open(_shareUrl,'_blank');
                      }
                    },
                    {
                      text: '豆瓣',
                      icon: '<img src="' + Config.server + '/images/o_img_db.png" width="48">',
                      onClick: function() {
                        var _shareUrl = 'http://shuo.douban.com/!service/share?';
                        _shareUrl += 'href=' + encodeURIComponent(msg.href);
                        _shareUrl += '&name=' + encodeURIComponent(msg.title);
                        _shareUrl += '&image=' + encodeURIComponent(msg.pictures || '');
                        window.open(_shareUrl,'_blank');
                      }
                    },
                    {
                      text: '人人网',
                      icon: '<img src="' + Config.server + '/images/o_img_renren.png" width="48">',
                      onClick: function() {
                        var _shareUrl = 'http://widget.renren.com/dialog/share?';
                        _shareUrl += 'link=' + encodeURIComponent(msg.href); 
                        _shareUrl += '&title=' + encodeURIComponent(msg.title); 
                        window.open(_shareUrl,'_blank');
                      }
                    },
                  ]
                ]
            }).open();
        }
    },
    io: {
        resolveLocalFileSystemURL() {

        }, 
        convertLocalFileSystemURL(filename) {
            return "file:///" + filename;
        }
    }, 
    uploader: {
        createUpload(url, options, callback) {
            let defaultOptions = {};
            let formData = new FormData();

            let task = {
                url: url + "?time=" + new Date().getTime(), 
                options: Utils.extend({}, options, defaultOptions),
                callback: callback,
                addData(name, value) {
                    formData.append(name, value);
                }, 
                addFile(path, params) {
                    let lastIndex = path.lastIndexOf("/");
                    if (lastIndex == -1) {
                        lastIndex = path.lastIndexOf("\\");
                    }
                    let name = path.substr(lastIndex + 1);
                    
                    window.ipcRenderer.send('newFile', path);

                    window.ipcRenderer.once("getFile", function(event, {data}) {
                        
                        let file = new File([data], name, {type:'image/jpg'});
                        formData.append(params.key, file);  

                        let xhr = new XMLHttpRequest();
                        xhr.onreadystatechange = function() {
                            if (xhr.readyState == 4 && xhr.status == 200) {
                                callback(xhr, xhr.status);
                            }
                        }
            
                        xhr.open(task.options.method, task.url, true);      

                        // 发送请求
                        xhr.send(formData);
                    });
                }, 
                start() {
                    
                }
            };
            
            return task;
        }
    }, 
    downloader: {
        startAll() {

        }, 
        enumerate(eachCB, state) {
            // 从数据库里获取
            Vue.prototype.$db.downloadRecord.orderBy('downloadDate').desc().toArray(function(array) {
                eachCB(array);
            });
        }, 
        createDownload(url, options) {
            var defaultOptions = {};
            var dtask = {
                id: '',
                url: url,
                state: -1,
                options: Utils.extend({}, options, defaultOptions),
                filename: '',
                downloadedSize: 0,
                totalSize: 0,
                callback: null,
                abort() {
                    vue.$f7.dialog.close();
                }, 
                addEventListener(eventName, callback) {
                    dtask.callback = callback;
                }, 
                pause() {
                    
                }, 
                resume() {
                    
                }, 
                setRequestHeader() {

                }, 
                start() {
                    // 发送信号
                    window.ipcRenderer.send('download', dtask.url);
                   
                    window.ipcRenderer.on("setFilename", function(event, filename) {
                        dtask.filename = filename;
                    });
                    window.ipcRenderer.on("pause", function(event, state) {
                        dtask.state = state;
                    });
                    window.ipcRenderer.on("progressing", function(event, jsonData) {
                        dtask.state = jsonData.state;
                    });
                    window.ipcRenderer.on("resume", function(event, state) {
                        dtask.state = state;
                    });
                    window.ipcRenderer.on("completed", function(event, jsonData) {
                        dtask.state = jsonData.state;
                        dtask.totalSize = jsonData.totalSize;
                        dtask.downloadedSize = jsonData.receivedSize;
                        // 重新设置保存路径
                        dtask.filename = jsonData.savePath;
                        if (dtask.callback) {
                            dtask.callback(dtask);
                        }
                    });
                    window.ipcRenderer.on("failed", function(event, state) {
                        dtask.state = state;
                        dtask.abort();
                    });
                }
            };

            return dtask;
        }
    }, 
    storage: {
        setItem(key, value) {

        }, 
        getItem(key) {

        }, 
        removeItem(key) {

        }
    }, 
    net: {
        XMLHttpRequest() {
            return new XMLHttpRequest();
        }
    }, 
    nativeObj: {
        Bitmap() {
            
            return {
                loadBase64Data() {
                
                }
            };
        }
    }, 
    nativeUI: {
        alert(text) {
            vue.$f7.dialog.alert(text);
        },
        showWaiting() {
            vue.$f7.preloader.close = vue.$f7.preloader.hide;
            vue.$f7.preloader.closeWaiting = vue.$f7.preloader.hide;
            vue.$f7.preloader.show();
            return vue.$f7.preloader;
        }, 
        close() {
            vue.$f7.preloader.hide();
        }, 
        closeWaiting() {
            vue.$f7.preloader.hide();
        }, 
        actionSheet(options, callback) {
            var buttons = [
                {
                    text: options.title || "请选择",
                    label: true
                },
            ];
            Utils.each(options.buttons, function(b, i) {
                buttons.push({
                    text: b.title, 
                    onClick: function(actions, e) {
                        if (callback) {
                            callback({index: 2});
                        }
                    }
                });
            });
            buttons.push({
                text: options.cancel,
                color: "red"
            });
            vue.$f7.actions.create({
                buttons: buttons
            }).open();
        }
    },
    zip: {
        compressImage(options, successCB, errorCB) {
            if (successCB) {
                successCB(options.srcPath);
            }
        }
    },
};

export default plus;